#include "Arduino.h"
#include "ML_Message.h"
#if defined ARDUINO_ARCH_ESP8266
#warning ML_Message:ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#elif defined ARDUINO_ARCH_ESP32
#warning ML_Message:ESP32
#include <SPI.h>
#include <WiFi.h>
#endif

//#define DEBUG 1

class ML_DEPS : public Stream
{
private:
  WiFiClient client;
  WiFiServer* server = NULL;
  int check = 0;
public:
  ML_DEPS(){
    server = new WiFiServer(1500);
    server->begin(); 
    #ifdef DEBUG
    Serial.println("WIFI Server Start.");
    #endif
  }
  bool checkClient(){
    if(check > 0){
      check--;
      return true;
    }
    if(client /*&& client.connected()*/){
      #ifdef DEBUG
      Serial.println("WIFI check client.OK");
      #endif
      check = 200;
      return true;
    }else{
      client = server->available();
      bool check = client && client.connected();
    #ifdef DEBUG
    Serial.print("WIFI check client.");
    Serial.println(check);
    #endif
      check = 10;
      return check;
    }

  }
  int available()
  {
    if(checkClient()){
      return client.available();
    }
    return 0;
  }
  int read()
  {
    if (checkClient())
    {
      int r = client.read();
    #ifdef DEBUG
    Serial.println("WIFI read.");
    Serial.println(r);
    #endif
      return r;
    }
    return -1;
  }
  int peek()
  {
    if (checkClient())
    {
      int r = client.peek();
    #ifdef DEBUG
    Serial.println("WIFI peek.");
    Serial.println(r);
    #endif
      return r;
    }
    return -1;
  }
  size_t write(uint8_t c)
  {
    if (checkClient())
    {
      size_t r = client.write(c);
    #ifdef DEBUG
    Serial.println("WIFI write.");
    Serial.println(r);
    #endif
      return r;
    }
    return 0;
  };
  void flush()
  {
    if (checkClient())
    {
      client.flush();
    }
  };
};
